<script lang="ts" setup>
  import { ref, toRefs, watch } from 'vue';
  import AuthorizeDrawer from '../role/AuthorizeDrawer.vue';
  import { getRoleList } from '/@/api/role';
  import { updateUserRole } from '/@/api/user';
  import { useMessage } from '/@/hooks/web/useMessage';

  const { createMessage } = useMessage();

  const loading = ref(false);

  const props = defineProps({
    visible: Boolean,
    user: Object,
  });

  const emits = defineEmits(['update:visible', 'success']);

  const { visible: vis, user } = toRefs(props);

  let treeData = ref([]);
  let treeDataSelected = ref([]) as any;
  async function getDataListAction() {
    loading.value = true;
    const { data } = await getRoleList({
      startIndex: 1,
      pageSize: 10000,
      roleName: '',
    });
    loading.value = false;
    function formatDataTree(s: any[]) {
      let t = [] as any;
      if (!s || s.length == 0) return undefined;
      s.forEach((e) => {
        t.push({
          label: e.roleName,
          value: e.id,
          children: formatDataTree(e.children),
        });
      });
      return t;
    }
    treeData.value = formatDataTree(data.list);
    treeDataSelected.value = user?.value?.roleVOList?.map((e: any) => e.id);
  }
  watch(
    vis,
    (nv) => {
      if (nv) {
        getDataListAction();
      }
    },
    { immediate: true },
  );

  const successHandler = async (p) => {
    loading.value = true;
    const { code, msg } = await updateUserRole({ userId: user?.value?.id, roleIds: p });
    loading.value = false;
    if (code == 200) {
      createMessage({
        message: msg,
      });
      emits('update:visible', false);
      emits('success');
    }
  };

  const cancelHandler = () => {
    emits('update:visible', false);
  };
</script>

<template>
  <AuthorizeDrawer
    :visible="visible"
    :tree-data="treeData"
    title="角色分配"
    :selected="treeDataSelected"
    :loading="loading"
    @success="successHandler"
    @cancel="cancelHandler"
  />
</template>

<style lang="less"></style>
